import dayjs from 'dayjs'
Page({
  data: {
    type: '-',
    records: [],
    groupedList: []
  },
  onShow() {
    this.getGroupedList()
  },
  updateType(e) {
    const {
      type
    } = e.detail
    this.setData({
      type
    })
    this.getGroupedList()
  },
  getGroupedList() {
    const {
      type
    } = this.data
    const records = wx.getStorageSync('recordList') || []
    this.setData({
      records
    })
    const newList = records.filter(r => r.type === type)
    if (newList.length === 0) {
      return []
    }
    const result = [{
      title: dayjs(newList[0].createdAt).format("YYYY-MM-DD"),
      total: '0',
      items: [newList[0]],
    }, ];
    for (let i = 1; i < newList.length; i++) {
      const current = newList[i];
      const last = result[result.length - 1];
      if (dayjs(last.title).isSame(dayjs(current.createdAt), "day")) {
        last.items.push(current);
      } else {
        result.push({
          title: dayjs(current.createdAt).format("YYYY-MM-DD"),
          total: '0',
          items: [current],
        });
      }
    }
    result.map(group => {
      group.total = group.items.reduce((sum, item) => {
        return sum + item.amount
      }, 0)
    })
    this.setData({
      groupedList: result
    })
  }
})